<?php
namespace App\Services;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
use App\Models\Linkslistsminapps;
use App\Services\LinkstokenService;
use App\Jobs\Miniappdisable;
use Log;

class LinkapiService
{
    public static function getLinkMiniapp($miniappStatus,$limitPv,$appid,$request)
    {
        if ($miniappStatus == 2) {
            if ($limitPv <= 100) {
                $miniapp = self::getPublicMiniapp(6);
            } else {
                $miniapp = self::getPublicMiniapp(3);
            }
        } else {
            $miniapp = self::getPrivateMiniapp($appid);
        }
        if ($miniapp["status"] == "error") return ["status"=>"error","msg"=>$miniapp["msg"]];
        $appid = $miniapp["appid"];
        $request->miniapp_type = $miniapp["miniapp_type"];
        $getToken = self::getAccessToken($appid,$request);
        if ($getToken["status"] == "error") return $getToken;
        $miniapp["access_token"] = $getToken["access_token"];
        return $miniapp;
    }

    public static function getPublicMiniapp($type)
    {
        $miniapp = Cache::get("public_miniapp_".$type);
        if(empty($miniapp)) {
            // 获取默认的微信小程序
            $linkMiniapp = Linkslistsminapps::getDefaultMinapp($type);
            if (empty($linkMiniapp)) return ["status"=>"error","msg"=>"暂无备用小程序"];
            $miniapp = ["appid"=>$linkMiniapp->appid,"miniapp_type"=>$linkMiniapp->miniapp_type,"version"=>$linkMiniapp->version];
            // 每次调用缓存2小时
            Cache::put("public_miniapp_".$type, $miniapp, 7200);
        }
        $miniapp["status"] = "success";
        return $miniapp;
    }

    public static function getPrivateMiniapp($appid)
    {
        $miniapp = Cache::get("private_miniapp_".$appid);
        if(empty($miniapp)) {
            // 获取默认的微信小程序
            $linkMiniapp = Linkslistsminapps::getLinksListsMinappsByAppid($appid);
            if (empty($linkMiniapp)) return ["status"=>"error","msg"=>"暂无备用小程序"];
            $miniapp = ["appid"=>$linkMiniapp->appid,"miniapp_type"=>$linkMiniapp->miniapp_type,"version"=>$linkMiniapp->version];
            // 每次调用缓存2小时
            Cache::put("private_miniapp_".$appid, $miniapp, 7200);
        }
        $miniapp["status"] = "success";
        return $miniapp;
    }

    public static function getAccessToken($appid,$request)
    {
        $accessToken = Cache::get('miniapp_token_'.$appid);
        if(empty($accessToken)) {
            $linksToken = LinkstokenService::getAccessToken($request,$appid);
            if ($linksToken["status"] == "error") {
                if ($linksToken["code"] == 50002) {
                    $minappsDisableStatus = Redis::hexists("links_lists_minapps_disable", $appid);
                    if (!$minappsDisableStatus) {
                        Miniappdisable::dispatch($appid,4)->delay(1);
                        Redis::hset("links_lists_minapps_disable", $appid, "1");
                    }
                }
            }
            if ($linksToken["status"] == "error") return ["status"=>"error","msg"=>$linksToken["msg"]];
            $accessToken = $linksToken["access_token"];
            // 每次调用缓存1小时
            Cache::put('miniapp_token_'.$appid, $accessToken, 7000);
        }
        return ["status"=>"success","access_token"=>$accessToken];
    }

    public static function getSchemeError($generate,$appid,$miniapp_type)
    {
        if ($generate["code"] == 50002 || $generate["code"] == 40013) {
            $minappsDisableStatus = Redis::hexists("links_lists_minapps_disable", $appid);
            if (!$minappsDisableStatus) {
                // 加入队列
                Miniappdisable::dispatch($appid,4)->delay(1);
                Redis::hset("links_lists_minapps_disable", $appid, "1");
            }
        } elseif ($generate["code"] == 40001 || $generate["code"] == 42001) {
            // Token过期需要获取新的
            Cache::forget('miniapp_token_'.$appid);
            // 30分钟内不强制刷新,避免多条链接抢Token导致上限
            $linksTokenReflesh = Cache::get('links_token_reflesh_'.$appid);
            if (empty($linksTokenReflesh)) {
                Cache::put('links_token_reflesh_'.$appid, "1", 1800);
                $forthAccessToken = LinkstokenService::forthAccessToken($appid,$miniapp_type);
                if ($forthAccessToken["status"] == "success") {
                    $accessToken =$forthAccessToken["access_token"];
                    // 每次调用缓存2小时
                    Cache::put('miniapp_token_'.$appid, $accessToken, 7000);
                }
            }
        }
    }

    public static function getLinkMiniPath($request,$version)
    {
        $pathquery = $request->pathquery;
        if (in_array($request->platfrom_type, [1,2,3,6,8,9,11,12,13,14,15,16])) {
            if ($version == 1) {
                $pathquery = str_replace("id=".$request->links_id, "", $pathquery);
                if ($pathquery == "") $pathquery = "a=1";
                // 兼容老版本
                $pathquery = $pathquery."&id=".$request->links_id."_".$request->record_id."&key=".$request->key."&timestamp=".$request->timestamp."&nsign=".$request->sign."&record_id=".$request->record_id;
            } else {
                if(strpos($pathquery,'id=') !== false){
                    $pathquery = $pathquery."&key=".$request->key."&timestamp=".$request->timestamp."&nsign=".$request->sign."&record_id=".$request->record_id;
                }else{
                    $pathquery = $pathquery."&key=".$request->key."&timestamp=".$request->timestamp."&nsign=".$request->sign."&id=".$request->links_id."&record_id=".$request->record_id;
                }
            }
        }
        return $pathquery;
    }

    public static function getSampleLinkMiniPath($request,$linkMiniappStatus)
    {
        if (in_array($linkMiniappStatus["platfrom_type"], [2,3,6,8,9,11,12])) {
            $path = "/pages/index/request";
            $query = "key=".$request->key."&timestamp=".$request->timestamp."&nsign=".$request->sign."&id=".$request->links_id."&record_id=".$request->record_id."&platfrom_type=".$linkMiniappStatus["platfrom_type"];
        } elseif (in_array($linkMiniappStatus["platfrom_type"], [14,15,16])) {
            $linkListSetting = Linkslistssetting::getLinksListsSetting($request->links_id);
            $path = "/pages/index/request";
            $query = "key=".$request->key."&timestamp=".$request->timestamp."&nsign=".$request->sign."&id=".$request->links_id."&record_id=".$request->record_id."&platfrom_type=".$linkMiniappStatus["platfrom_type"]."&sph_id=".$linkListSetting->sph_id."&sph_spid=".$linkListSetting->sph_spid."&sph_img=".$linkListSetting->sph_img;
        } elseif (in_array($linkMiniappStatus["platfrom_type"], [1,13])) {
            $path = "/pages/index/request";
            $query = "key=".$request->key."&timestamp=".$request->timestamp."&nsign=".$request->sign."&id=".$request->links_id."&record_id=".$request->record_id."&platfrom_type=".$linkMiniappStatus["platfrom_type"]."&url=".$linkMiniappStatus["msg"];
        } else {
            $pathParamas = explode("?",$linkMiniappStatus["path"]);
            $path = $pathParamas[0];
            $query = count($pathParamas) > 1 ? $pathParamas[1] : "";
        }
        return ["path"=>$path,"query"=>$query];
    }
}
